package org.zju.demo.shoppingdemo.task;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.zju.demo.shoppingdemo.activity.BaseActivityInterface;
import org.zju.demo.shoppingdemo.model.response.BaseResponse;
import org.zju.demo.shoppingdemo.utils.Constant;

/**
 * Created by ZJDX on 2015/9/8.
 */
public class HttpAsyncTask extends AsyncTask<Object, Object, BaseResponse>{
    private static HttpClient client = new DefaultHttpClient();
    /**
     * bind to some activity
     * */
    protected BaseActivityInterface activityInterface;
    /***
     * bind to some response
     */
    protected BaseResponse response;

    protected Class clazz;

    public HttpAsyncTask(BaseActivityInterface activityInterface, Class clazz) {
        this.activityInterface = activityInterface;
        this.clazz = clazz;
    }

    private JSONObject doPost(String url, String json) throws Exception{
        HttpPost post = new HttpPost(url);
        JSONObject result = null;
        post.addHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(json, HTTP.UTF_8));
        HttpResponse httpResponse = client.execute(post);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String resultStr = EntityUtils.toString(httpResponse.getEntity());
            result = new JSONObject(resultStr);
        } else {
            result = new JSONObject();
        }
        result.put("status", httpResponse.getStatusLine().getStatusCode());
        return result;
    }

    private JSONObject doGet(String url) throws Exception {
        HttpGet get = new HttpGet(url);
        HttpResponse httpResponse = client.execute(get);
        JSONObject result = null;
        if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String resultStr = EntityUtils.toString(httpResponse.getEntity());
            result = new JSONObject(resultStr);
        } else {
            result = new JSONObject();
        }
        result.put("status", httpResponse.getStatusLine().getStatusCode());
        return result;
    }

    // activity do something in UI thread
    @Override
    protected void onPreExecute() {
        activityInterface.onPreExecute();
    }

    /**
     * send request to web service
     * @param params, length = 3, first is url, second is method, third is json string
     * @return response
     */
    @Override
    protected BaseResponse doInBackground(Object[] params) {
        assert(params.length == 3);
        String url = (String) params[0];
        String method = (String) params[1];
        String json = (String) params[2];
        JSONObject result = null;
        try {
            if (method.equals(Constant.GET_METHOD)) {
                result = doGet(url);
            } else if (method.equals(Constant.POST_METHOD)) {
                result = doPost(url, json);
            }
            Log.i("HTTPASYNCTask", result.toString());
            // try to bind the result to some concrete response class
            Gson gson = new Gson();
            response = (BaseResponse)gson.fromJson(result.toString(), clazz);
            response.doExtra();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
    /**
     * deal with object o in UI thread
    * */
    @Override
    protected void onPostExecute(BaseResponse result) {
        activityInterface.onResponseMessage(result);
    }
    /**
     * do update in UI thread
     * */
    @Override
    protected void onProgressUpdate(Object[] values) {
        activityInterface.onProgressUpdate(values);
    }
}
